package cn.scy.business.service;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.scy.base.PageResult;
import cn.scy.business.domain.entity.NumMemberInfo;
import cn.scy.business.domain.entity.guangzlt.NumNumberInfo;
import cn.scy.business.domain.param.NumMemberInfoParam;
import cn.scy.business.mapper.NumMemberInfoMapper;
import cn.scy.business.mapper.guangzlt.NumNumberInfoMapper;
import cn.scy.exception.BusinessException;
import cn.scy.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 报备管理-号码身份表 服务实现类
 *
 * @author scy
 * @since 2025-04-26
 */
@Service
public class NumMemberInfoServiceImpl extends ServiceImpl<NumMemberInfoMapper, NumMemberInfo> implements NumMemberInfoService {

    @Resource
    private NumNumberInfoMapper numberInfoMapper;

    @Override
    public PageResult<NumMemberInfo> listPage(NumMemberInfoParam param) {
        // 构建分页对象
        Page<NumMemberInfo> pageQuery = PageUtil.convert2PageQuery(param);
        // 构建查询参数对象
        LambdaQueryWrapper<NumMemberInfo> query = new LambdaQueryWrapper<>();
        query.select(
                NumMemberInfo::getId,
                NumMemberInfo::getName,
                NumMemberInfo::getIdentityCard,
                NumMemberInfo::getCreateTime
        );
        query.like(StrUtil.isNotBlank(param.getName()), NumMemberInfo::getName, param.getName());
        query.eq(StrUtil.isNotBlank(param.getIdentityCard()), NumMemberInfo::getIdentityCard, param.getIdentityCard());
        query.orderByDesc(NumMemberInfo::getCreateTime).orderByAsc(NumMemberInfo::getId);
        // 执行查询
        Page<NumMemberInfo> pageData = this.page(pageQuery, query);

        // 对查询结果进行脱敏处理
        List<NumMemberInfo> desensitizedRecords = pageData.getRecords().stream()
                .map(record -> {
                    // 复制原始对象，避免修改数据库记录
                    NumMemberInfo desensitizedRecord = new NumMemberInfo();
                    BeanUtils.copyProperties(record, desensitizedRecord);
                    // 对身份证号进行脱敏处理
                    desensitizedRecord.setIdentityCard(DesensitizedUtil.idCardNum(record.getIdentityCard(),4,4));
                    desensitizedRecord.setIdCardBackImage(null);
                    desensitizedRecord.setIdCardFrontImage(null);
                    desensitizedRecord.setLiveFaceImage(null);
                    return desensitizedRecord;
                })
                .collect(Collectors.toList());

        return PageUtil.convert2PageResult(pageData, desensitizedRecords);
    }

    @Override
    public NumMemberInfo info(String id) {
        NumMemberInfo info = this.getById(id);
        NumMemberInfo desensitizedRecord = new NumMemberInfo();
        BeanUtils.copyProperties(info, desensitizedRecord);
        desensitizedRecord.setIdentityCard(DesensitizedUtil.idCardNum(info.getIdentityCard(),4,4));
        return desensitizedRecord;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addMember(NumMemberInfo numMemberInfo) {
        // 校验参数
        checkParam(numMemberInfo);
        // 保存数据
        return this.save(numMemberInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editMember(NumMemberInfo numMemberInfo) {
        //如果没有改身份证号码传入的身份证号带*
        if (!StrUtil.isBlank(numMemberInfo.getIdentityCard()) && numMemberInfo.getIdentityCard().contains("*")) {
            NumMemberInfo numInfo = this.getById(numMemberInfo.getId());
            numMemberInfo.setIdentityCard(numInfo.getIdentityCard());
        }
        // 校验参数
        checkParam(numMemberInfo);
        // 更新数据
        return this.updateById(numMemberInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteMember(String id) {
        // 校验是否有号码
        boolean exists = numberInfoMapper.exists(
                new LambdaQueryWrapper<NumNumberInfo>()
                        .eq(NumNumberInfo::getMemberId, id)
        );
        if (exists) {
            throw new BusinessException("该身份名下已有号码数据，无法删除");
        }
        // 删除数据
        return this.removeById(id);
    }

    private void checkParam(NumMemberInfo numMemberInfo) {
        // 校验身份证号
        if (StrUtil.isBlank(numMemberInfo.getIdentityCard())) {
            throw new BusinessException("身份证号不能为空");
        }
        if (!IdcardUtil.isValidCard(numMemberInfo.getIdentityCard())) {
            throw new BusinessException("身份证号不合法");
        }
        // 校验身份证号不能和已有数据重复
        NumMemberInfo one = this.lambdaQuery()
                .eq(NumMemberInfo::getIdentityCard, numMemberInfo.getIdentityCard())
                .ne(StrUtil.isNotBlank(numMemberInfo.getId()), NumMemberInfo::getId, numMemberInfo.getId())
                .one();
        if (ObjectUtil.isNotNull(one)) {
            throw new BusinessException("身份证号已存在");
        }
    }

}
